<template>
    <div class="container">
        <div id="mapContainer" class="mapContainer"></div>
        <div class="search-container" v-if="isSearch">
            <div class="input-wrapper">
                <span class="search-label">搜索</span> <input id="searchText" type="text" class="search-text" placeholder="请输入搜索词" />
            </div>
        </div>
    </div>
</template>

<script>
import {lazyAMapApiLoaderInstance} from 'vue-amap';

export default {
    data() {
        return {
            searchText: ''
        };
    },
    props: {
        //经纬度坐标 [123.45,80.34]
        position: {
            type: Array,
            default: () => {
                return [];
            }
        },
        //缩放级别
        zoom: {
            type: Number,
            default: 16
        },
        //模式:可选'normal'(显示商店定位)、'positionPicker'(商店位置拖拽选择)
        mode: {
            type: String,
            default: 'normal'
        },
        //是否加载POI搜索
        isSearch: {
            type: Boolean,
            default: false
        },
    },
    mounted() {
        //初始化加载地图
        lazyAMapApiLoaderInstance.load().then(() => {
            let option = {};
            if (this.position.length) {
                option.center = this.position;
            }
            if (this.zoom) {
                option.zoom = this.zoom;
            }
            option.scrollWheel = false;
            this.map = new AMap.Map('mapContainer', option);
            this.AMap = AMap;

            //加载poi搜索组件
            if (this.isSearch) {
                this._initPoiPicker(AMapUI);
            }

            if (this.mode === 'positionPicker') {
                this._initPositionPicker(AMapUI);
            } else {
                //normal模式 只显示position位置或者设备当前定位位置
                if (!this.position.length) {
                    //未传location定位当前设备位置
                    this._getCurrentPositon();
                } else {
                    this.addMarker(this.position);
                }
            }
        });
    },
    methods: {
        addMarker(position, message) {
            const AMap = this.AMap;
            const map = this.map;
            // 创建一个 Marker 实例
            var marker = new AMap.Marker({
                position: new AMap.LngLat(...position), // 经纬度构成的一维数组[116.39, 39.9]
                title: ''
            });
            // 将创建的点标记添加到已有的地图实例
            map.add(marker);

            //处理InfoWindow
            if (message) {
                let infoWindow = new AMap.InfoWindow({
                    position: position,
                    offset: new AMap.Pixel(0, -20), //纵向偏移
                    showShadow: true, //显示阴影
                    content: message //文字内容
                });

                infoWindow.open(map);
            }

            this.map.setCenter(marker.getPosition());
        },
        //初始化拖拽选择
        _initPositionPicker(AMapUI) {
            //加载拖拽选择插件 positionPicker
            AMapUI.loadUI(['misc/PositionPicker'], (PositionPicker) => {
                var positionPicker = new PositionPicker({
                    mode: 'dragMap', //设定为拖拽地图模式，可选'dragMap'、'dragMarker'，默认为'dragMap'
                    map: this.map //依赖地图对象
                });
                positionPicker.on('success', (positionResult) => {
                    // console.log(positionResult);
                    this.$emit('selectLocation', positionResult);
                });
                positionPicker.on('fail', (positionResult) => {
                    console.info(positionResult);
                });
                //开始拖拽选择
                positionPicker.start();
            });
        },
        //初始化poi搜索
        _initPoiPicker(AMapUI) {
            //加载拖拽选择插件 PoiPicker
            AMapUI.loadUI(['misc/PoiPicker'], (PoiPicker) => {
                var poiPicker = new PoiPicker({
                    input: 'searchText' //输入框id
                });
                //监听poi选中信息
                poiPicker.on('poiPicked', (poiResult) => {
                    //用户选中的poi点信息
                    let poi = poiResult.item;
                    this.addMarker([poi.location.lng, poi.location.lat], poi.name);
                });
            });
        },
        _getCity() {
            if (!this.AMap) {
                return;
            }
            const AMap = this.AMap;
            AMap.plugin('AMap.CitySearch', () => {
                const citySearch = new AMap.CitySearch();
                citySearch.getLocalCity((status, result) => {
                    if (status === 'complete' && result.info === 'OK') {
                        // 查询成功，result即为当前所在城市信息
                        console.log('amap-_getCity',result);
                    }
                });
            });
        },
        _getCurrentPositon() {
            const AMap = this.AMap;
            const map = this.map;
            var geolocation = new AMap.Geolocation({
                // 是否使用高精度定位，默认：true
                enableHighAccuracy: false,
                // 设置定位超时时间，默认：无穷大
                timeout: 10000,
                // 定位按钮的停靠位置的偏移量，默认：Pixel(10, 20)
                buttonOffset: new AMap.Pixel(10, 20),
                //  定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
                zoomToAccuracy: true,
                //  定位按钮的排放位置,  RB表示右下
                buttonPosition: 'RB'
            });

            geolocation.getCurrentPosition();
            AMap.event.addListener(geolocation, 'complete', (data) => {
                console.log('amap-addListener',data);
            });
            AMap.event.addListener(geolocation, 'error', (err) => {
                console.log('amap-addListener-err',err);
            });
            map.addControl(geolocation);
        },
    }
};
</script>
<style lang="stylus" scoped>
@import '~assets/main.styl'

.container{
    position relative
    .mapContainer {
        position relative
        height 100vh
        width 100vw
    }
    .search-container{
        position fixed
        top vw(20)
        left vw(20)
        width vw(250)
        background-color grayF
        padding smallMargin smallMargin
        border-radius radius
        min-width vw(20)
        border-width 0
        box-shadow 0 2px 6px 0 rgba(114, 124, 245, .5)
        .input-wrapper{
            display flex
            justify-content center
            .search-label{
                line-height vw(15)
                flex 0 0 vw(40)
                padding titleMargin titleMargin
                display inline-block
                font-size word12
                font-weight bold
                color grayF
                background-color main-color
                border 1px solid main-color
                text-align center
            }
            .search-text{
                flex 0 1 vw(200)
                border 1px solid main-color
                padding titleMargin titleMargin
                font-size word12
                line-height vw(15)
            }
        }
    }
}
</style>
